package com.qf.bargaintask;

import com.qf.service.BargainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

@EnableScheduling
@Component
@Slf4j
public class BargainTask {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private BargainService bargainService;

    @Autowired
    private JavaMailSender javaMailSender;

    @Scheduled(cron = "0 46 21 * * ?")
    public void dueTask(){
        //查询明天到期的合同id
        List<Integer> idList= bargainService.findDueIds();

        if(idList != null && idList.size() > 0) {
            log.info("【定时任务】 定时发送邮件，提醒明天到期. ids = {}",idList);

            //先遍历输出一下
            for (Integer integer : idList) {
                System.out.println(integer);
            }
            StringBuilder str=new StringBuilder();
            for (Integer integer : idList) {
                //将合同编号拼接成字符串
                str.append(integer+"、");
            }
            //截取字符串，将最后一个"、"省略
            String s=str.substring(0,str.length()-1);
            System.out.println(s);

            try {
                //1. 创建邮件对象.
                MimeMessage msg = javaMailSender.createMimeMessage();
                //2. 给msg邮件设置信息.
                MimeMessageHelper msgHelper = new MimeMessageHelper(msg,true);
                //2.1 收件人
                msgHelper.addTo("1364224576@qq.com");
                //2.2 主题.
                msgHelper.setSubject("合同到期提醒邮件");
                //2.3 内容
                msgHelper.setText("text/html;charset=utf-8","尊敬的公司领导，编号为："+s+"，的合同将于明天到期，请及时查看。");
                //2.4
                msgHelper.setFrom(from);

                javaMailSender.send(msg);
            } catch (MessagingException e) {
                e.printStackTrace();
                System.out.println("邮件发送失败");
            }
        }

    }
}
